package com.google.code.p.localspinner.http;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.google.code.p.localspinner.AppUtils;
import com.google.code.p.localspinner.io.IOUtils;
/**
 * TODO: javadoc me
 * 
 * @author liangj01
 *
 */
public class UserAgent{
    
  
    private HttpClient cliet = new DefaultHttpClient();
    private boolean header = false;
    public UserAgent(){}
    public UserAgent(boolean header){
      this.header = header;
    }
    
    public InputStream getUrlAsStream(String url) throws HttpRequestException{
      
      HttpGet get = new HttpGet(url);
      if(header){
        get.setHeader("Accept-Language", "en_US");
        get.setHeader("Accept", "application/xml");
      }
      
      HttpResponse res;
      try {
        Log.d(UserAgent.class.toString(), url);
        res = cliet.execute(get);
        return res.getEntity().getContent();
      } catch (Exception e) {
        get.abort();
        throw new HttpRequestException("Http request failed", e);
      }
    }
    
    
    public String getUrlAsString(String url) throws HttpRequestException{
        InputStream in = null;
        try {
            in = getUrlAsStream(url);
            return IOUtils.toString(in); 
        } catch (IOException e) {
            throw new HttpRequestException(e.getMessage(), e);
        }finally{
            AppUtils.closeQuietly(in);
        }
        
    }
}